<script setup>
// 脚本部分完全保留原始逻辑，未做任何修改
import { ref, computed, onMounted, watch } from "vue";
import { postBorrowBook } from "@/api/borrow";
import { getReaderListAPI } from "@/api/reader";
import { getBookListAPI } from "@/api/manageBook";
import { ElMessage } from "element-plus";

const emit = defineEmits(["success"]);

const visibleDrawer = ref(false);
const loading = ref(false);
const readerLoading = ref(false);
const bookLoading = ref(false);

const info = ref({
  card: "",
  bookNumber: null,
  lendingTime: "",
  days: 10,
});

const rules = {
  card: [{ required: true, message: "请输入卡号", trigger: "blur" }],
  bookNumber: [{ required: true, message: "请输入图书编号", trigger: "blur" }],
  days: [
    { required: true, message: "请输入借阅天数", trigger: "blur" },
    { type: "number", message: "请输入数字", trigger: "blur" },
  ],
};

const readerList = ref([]);
const readerParams = ref({
  pagenum: 1,
  pagesize: 10,
  card: "",
});
const total = ref(0);

const bookList = ref([]);
const reader_Book = ref({
  pagenum: 1,
  pagesize: 10,
  number: "",
});
const total_book = ref(0);

const readerOptions = computed(() =>
  readerList.value.map((item) => ({ value: item.card, label: item.card }))
);

const bookOptions = computed(() =>
  bookList.value.map((item) => ({ value: item.number, label: item.number }))
);

const getReaderList = async (params = readerParams.value) => {
  readerLoading.value = true;
  try {
    const res = await getReaderListAPI(params);
    readerList.value = res.data.data || [];
    total.value = res.data.total || 0;
  } catch (error) {
    console.error("获取读者列表失败", error);
  } finally {
    readerLoading.value = false;
  }
};

const getBookList = async (params = reader_Book.value) => {
  bookLoading.value = true;
  try {
    const res = await getBookListAPI(params);
    bookList.value = res.data.data || [];
    total_book.value = res.data.total || 0;
  } catch (error) {
    console.error("获取图书列表失败", error);
  } finally {
    bookLoading.value = false;
  }
};

const switchDrawer = () => {
  visibleDrawer.value = true;
};

const handleCurrentChange = (val) => {
  info.value.card = val?.card || "";
};

const handleCurrentChange_book = (val) => {
  info.value.bookNumber = val?.number || null;
};

const remoteMethod = (query) => {
  readerParams.value.card = query;
  readerParams.value.pagenum = 1;
  getReaderList();
};

const remoteMethod_bookName = (query) => {
  reader_Book.value.number = query;
  reader_Book.value.pagenum = 1;
  getBookList();
};

const handleSizeChange = (val) => {
  readerParams.value.pagesize = val;
  getReaderList();
};

const handlePageChange = (val) => {
  readerParams.value.pagenum = val;
  getReaderList();
};

const handleSizeChange_book = (val) => {
  reader_Book.value.pagesize = val;
  getBookList();
};

const handlePageChange_book = (val) => {
  reader_Book.value.pagenum = val;
  getBookList();
};

const formRef = ref(null);

const submitForm = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    info.value.lendingTime = new Date().toISOString();
    await postBorrowBook(info.value);
    ElMessage.success("借书成功");
    visibleDrawer.value = false;
    emit("success");
  } catch (error) {
    if (error.name !== "Error") {
      console.error("表单验证失败", error);
    } else {
      console.error("借书失败", error);
      ElMessage.error("借书失败，请重试");
    }
  } finally {
    loading.value = false;
  }
};

const resetFormData = () => {
  info.value = {
    card: "",
    bookNumber: null,
    lendingTime: "",
    days: 10,
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const closeDialog = () => {
  visibleDrawer.value = false;
  resetFormData();
};

watch(visibleDrawer, (newVal) => {
  if (!newVal) {
    resetFormData();
  }
});

onMounted(() => {
  getReaderList();
  getBookList();
});

defineExpose({
  switchDrawer,
});
</script>

<template>
  <!-- 抽屉 -->
  <el-drawer v-model="visibleDrawer" title="借书" direction="rtl" size="50%">
    <el-form
      ref="formRef"
      :model="info"
      :rules="rules"
      label-width="80px"
      style="
        padding: 20px;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      "
    >
      <!-- 卡号选择 -->
      <el-form-item label="卡号" prop="card">
        <el-select
          v-model="info.card"
          filterable
          remote
          reserve-keyword
          remote-show-suffix
          :remote-method="remoteMethod"
          :loading="readerLoading"
          style="width: 300px"
        >
          <el-option
            v-for="item in readerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 读者表格及分页 -->
      <el-table
        :data="readerList"
        highlight-current-row
        style="
          width: 100%;
          margin: 10px 0;
          border: 1px solid #eee;
          border-radius: 4px;
        "
        @current-change="handleCurrentChange"
        :row-key="(item) => item.id || item.card"
        :loading="readerLoading"
      >
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column property="name" label="姓名" />
        <el-table-column property="card" label="卡号" />
        <template #empty>
          <el-empty description="没有数据" />
        </template>
      </el-table>

      <el-pagination
        v-model:current-page="readerParams.pagenum"
        v-model:page-size="readerParams.pagesize"
        :page-sizes="[5, 10, 20]"
        background
        layout="total, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin: 10px 0 20px; justify-content: flex-end"
      />

      <!-- 图书编号选择 -->
      <el-form-item label="图书编号" prop="bookNumber">
        <el-select
          v-model="info.bookNumber"
          filterable
          remote
          reserve-keyword
          remote-show-suffix
          :remote-method="remoteMethod_bookName"
          :loading="bookLoading"
          style="width: 300px"
        >
          <el-option
            v-for="item in bookOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 图书表格及分页 -->
      <el-table
        :data="bookList"
        highlight-current-row
        style="
          width: 100%;
          margin: 10px 0;
          border: 1px solid #eee;
          border-radius: 4px;
        "
        @current-change="handleCurrentChange_book"
        :row-key="(item) => item.id || item.number"
        :loading="bookLoading"
      >
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column property="number" label="图书编号" />
        <el-table-column property="bookName" label="图书名称" />
        <el-table-column property="location" label="图书位置" />
        <template #empty>
          <el-empty description="没有数据" />
        </template>
      </el-table>

      <el-pagination
        v-model:current-page="reader_Book.pagenum"
        v-model:page-size="reader_Book.pagesize"
        :page-sizes="[5, 10, 20]"
        background
        layout="total, prev, pager, next"
        :total="total_book"
        @size-change="handleSizeChange_book"
        @current-change="handlePageChange_book"
        style="margin: 10px 0 20px; justify-content: flex-end"
      />

      <!-- 借阅天数 -->
      <el-form-item label="借阅天数" prop="days" style="width: 300px">
        <el-input-number
          v-model="info.days"
          min="1"
          max="90"
          controls-position="right"
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item style="margin-top: 15px">
        <el-button
          :loading="loading"
          type="primary"
          @click="submitForm"
          style="margin-right: 10px"
        >
          确认
        </el-button>
        <el-button @click="closeDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped>
/* 表格表头样式优化 */
::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

/* 表格行悬停效果 */
::v-deep .el-table__row:hover > td {
  background-color: #f9fafb !important;
}

/* 选择器和输入框底部间距 */
::v-deep .el-select,
::v-deep .el-input-number {
  margin-bottom: 5px;
}

/* 分页组件样式调整 */
::v-deep .el-pagination {
  font-size: 13px;
}

/* 按钮样式微调 */
::v-deep .el-button {
  padding: 8px 16px;
}
</style>
